package org.noote.libs.sogle;

import android.util.FloatMath;

public class Vector3D {
	public float x=0, y=0, z=0;
	
	public Vector3D()
	{
	}
	
	public Vector3D(float x, float y, float z)
	{
		this.x=x; this.y=y; this.z=z;
	}
	public Vector3D(Vector3D v)
	{
		this.x = v.x; this.y = v.y; this.z = v.z;
	}
	
	public void set(Vector3D v) {
		this.x = v.x; this.y = v.y; this.z = v.z;
	}
	
	public void set(float x, float y, float z) {
		this.x=x; this.y=y; this.z=z;
	}

	public float getSquaredLenght()
	{
		return (x*x+y*y+z*z);
	}
	
	public float getLenght()
	{
		return FloatMath.sqrt(getSquaredLenght());
	}
	
	public void normalize()
	{
		float mag = getLenght();
		if(mag>0.0f)
		{
			x /= mag; y /= mag; z /= mag;
		}
		else
			x = y = z = 0.0f;
	}

	public static float dotProduct(Vector3D v1, Vector3D v2)
	{
		return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z);
	}

	public static Vector3D crossProduct(Vector3D v1, Vector3D v2)
	{
		return new Vector3D(	( v1.y * v2.z ) - ( v1.z * v2.y ), ( v1.z * v2.x ) - ( v1.x * v2.z ), ( v1.x * v2.y ) - ( v1.y * v2.x )	);
	}
	
	public static Vector3D mul(Vector3D v, float f)
	{
		return new Vector3D(v.x*f, v.y*f, v.z*f);
	}
	
	public static Vector3D add(Vector3D v1, Vector3D v2)
	{
		return new Vector3D(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z);
	}
	
	public static Vector3D sub(Vector3D v1, Vector3D v2)
	{
		return new Vector3D(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z);
	}
	
	public static Vector3D normalize(Vector3D v)
	{
		Vector3D vn = new Vector3D(v);
		vn.normalize();
		return vn;
	}	
	
	public static Vector3D translateAndScale(Vector3D v, Vector3D translation, float scale)
	{
		Vector3D ret = new Vector3D();
		ret.x = translation.x + ( v.x * scale);
		ret.y = translation.y + ( v.y * scale);
		ret.z = translation.z + ( v.z * scale);
		return ret;
	}
	
	public static Vector3D build_tri_normal(Vector3D p1, Vector3D p2, Vector3D p3)
	{
		float x = (p2.y-p1.y)*(p3.z-p1.z) - (p2.z-p1.z)*(p3.y-p1.y);
		float y = (p2.z-p1.z)*(p3.x-p1.x) - (p2.x-p1.x)*(p3.z-p1.z);
		float z = (p2.x-p1.x)*(p3.y-p1.y) - (p2.y-p1.y)*(p3.x-p1.x);
		float len = (float) Math.sqrt((x*x)+(y*y)+(z*z));
		return new Vector3D(x/len, y/len, z/len);
	}
}
